<template>
  <div class="category">
    <van-nav-bar title="分类">
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </van-nav-bar>
    <van-tree-select :items="items" :main-active-index.sync="active">
      <template #content>
        <van-grid :column-num="3">
          <van-empty v-if="!category.length" description="该列表下没有商品哦~" />
          <van-grid-item
            v-else
            v-for="(item,index) in category"
            :key="index"
            :icon="'http://localhost:3000'+item.img"
            :text="item.catename"
            :to="'/category/'+item.id"
          />
        </van-grid>
      </template>
    </van-tree-select>
  </div>
</template>
<script>
export default {
  data() {
    return {
      activeKey: 0,
      active: 0,
      items: [],
      category: []
    };
  },
  created() {
    this.getData();
    this.getSecCate(this.active);
  },
  watch: {
    active: {
      handler(newVal, oldVal) {
        this.getSecCate(newVal);
      }
    }
  },
  methods: {
    getData() {
      this.$http.get("getcate").then(res => {
        res.data.list.forEach(item => {
          this.items.push({
            text: item.catename
          });
        });
      });
    },
    getSecCate(index) {
      this.$http.get("getcate").then(res => {
        this.category = res.data.list[index].children;
        if(res.data.list[index].children==undefined){
          this.category=[];
        }
      });
    }
  }
};
</script>
<style>
.van-tree-select__content {
  flex: 3;
}
.van-icon__image {
  width: 65px;
  height: 85px;
}
.van-grid-item__text {
  font-size: 15px;
}
.category .van-nav-bar {
  position: fixed;
  width: 100%;
  top: 0;
}
</style>